<script setup>
import TopHeader from '@/views/edu/common/TopHeader.vue'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { watch } from 'vue'
import {
  countDown,
  countDownInfo,
  initCountDownInfo
} from '@/utils/countDown.js'
import { getEmailCode, updatePswByEmail } from '@/api/user.js'
import throttle from 'lodash/throttle.js'
initCountDownInfo()
const particlesLoaded = async container => {
  console.log('Particles container loaded', container)
}
const confirm = throttle(async () => {
  if (
    formRules.mail[0].validator(formRules.mail[0], formValidate.value.mail) &
      formRules.password[0].validator(
        formRules.password[0],
        formValidate.value.password
      ) &&
    formRules.confirmPassword[0].validator(
      formRules.confirmPassword[0],
      formValidate.value.confirmPassword
    )
  ) {
    const { mail, code, password, confirmPassword } = formValidate.value
    const allData = {
      email: mail,
      code: code,
      newPwd: password,
      rePwd: confirmPassword
    }
    const result = await updatePswByEmail(allData)
    console.log('result:' + result)
    if (result.data) {
      ElMessage.success('密码修改成功，请重新登录')
      active.value = 1
    } else {
      ElMessage.error('验证码错误或密码格式错误')
    }
  } else {
    ElMessage.error('请检查输入是否正确')
  }
}, 5000)

const getVc = async () => {
  if (formRules.mail[0].validator(formRules.mail[0], formValidate.value.mail)) {
    const email = formValidate.value.mail
    const code = await getEmailCode(email)
    if (code) {
      ElMessage.success('验证码获取成功')
    }
    countDown(initCountDownInfo)
  } else {
    ElMessage.error('请先验证邮箱')
  }
}

const formValidate = ref({
  mail: '', //邮箱
  code: '', //验证码
  password: '', //新密码
  confirmPassword: '' //确认密码
})

const formRules = {
  mail: [
    {
      key: 'mail',
      message: '请输入正确的邮箱',
      trigger: ['input', 'blur'],
      required: true,
      validator: (rule, value) =>
        /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)
    }
  ],
  code: [
    {
      key: 'code',
      message: '请输入正确的验证码',
      trigger: ['input', 'blur'],
      required: true,
      validator: (rule, value) => /^[a-zA-Z0-9_-]{6}$/.test(value)
    }
  ],
  password: [
    {
      key: 'password',
      message: '密码需为 5-20 位，且为数字和字母组合',
      trigger: ['input', 'blur'],
      required: true,
      validator: (rule, value) =>
        /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{5,20}$/.test(value)
    }
  ],
  confirmPassword: [
    {
      key: 'confirmPassword',
      message: '两次密码不一致',
      trigger: ['input', 'blur'],
      validator: (rule, value) => value === formValidate.value.password
    }
  ]
}

const active = ref(0)
const form = ref(null)
const isFormValid = ref(false)

const next = () => {
  form.value.validate(valid => {
    if (valid) {
      if (active.value++ > 1) {
        active.value = 0
      }
    } else {
      isFormValid.value = false
      const firstInvalidField = Object.keys(formRules).find(field => {
        const fieldRules = formRules[field]
        return fieldRules.some(rule => {
          try {
            return !rule.validator(rule, formValidate.value[field])
          } catch (error) {
            return error.message
          }
        })
      })
      const errorMessage = formRules[firstInvalidField][0].message
      ElMessage.error(errorMessage)
    }
  })
}

watch(isFormValid, newValue => {
  const nextButton = document.querySelector('.el-card footer.el-button')
  if (nextButton) {
    nextButton.disabled = !newValue
  }
})

const options = {
  fpsLimit: 60,
  particles: {
    number: {
      value: 60,
      density: {
        enable: true,
        value_area: 1000
      }
    },
    color: {
      value: ['#344455', '#ffffff']
    },
    shape: {
      type: 'edge',
      stroke: {
        width: 0,
        color: '#000000'
      },
      polygon: {
        nb_sides: 5
      },
      image: {
        src: 'img/github.svg',
        width: 100,
        height: 100
      }
    },
    opacity: {
      value: 0.5,
      random: false,
      anim: {
        enable: false,
        speed: 1,
        opacity_min: 0.1,
        sync: false
      }
    },
    size: {
      value: 4,
      random: true,
      anim: {
        enable: false,
        speed: 40,
        size_min: 0.1,
        sync: false
      }
    },
    line_linked: {
      enable: true,
      distance: 50,
      color: '#fff',
      opacity: 0.5,
      width: 1
    },
    move: {
      enable: true,
      speed: 3,
      direction: 'none',
      random: false,
      straight: false,
      out_mode: 'out',
      bounce: false,
      attract: {
        enable: false,
        rotateX: 600,
        rotateY: 1200
      }
    }
  },
  retina_detect: true
}
</script>

<template>
  <div>
    <vue-particles
      id="tsparticles"
      @particles-loaded="particlesLoaded"
      :options="options"
    />
  </div>

  <div>
    <!-- 粒子动画 -->

    <TopHeader />

    <div style="display: flex; justify-content: center; margin-top: 50px">
      <el-steps style="width: 800px" :active="active" finish-status="success">
        <el-step title="重置密码" />
        <el-step title="完成修改" />
      </el-steps>
    </div>

    <div style="display: flex; justify-content: center; margin-top: 50px">
      <el-card style="width: 480px">
        <template #header>
          <div class="card-header">
            <span style="font-size: 24px">重置密码</span>
          </div>
        </template>
        <el-form
          :rules="formRules"
          :model="formValidate"
          ref="form"
          label-width="100px"
        >
          <el-form-item label="邮箱" v-show="active === 0" prop="mail">
            <el-input
              v-model="formValidate.mail"
              placeholder="请输入邮箱"
              clearable
            />
          </el-form-item>
          <el-form-item label="验证码" v-show="active === 0" prop="code">
            <span style="width: 200px">
              <el-input
                v-model="formValidate.code"
                placeholder="请输入验证码"
              />
            </span>

            <span style="margin-left: 20px">
              <el-button
                type="primary"
                @click="getVc"
                :disabled="countDownInfo.running"
              >
                {{ countDownInfo.text }}
              </el-button>
            </span>
          </el-form-item>
          <el-form-item label="新密码" v-show="active === 0" prop="password">
            <el-input
              v-model="formValidate.password"
              type="password"
              placeholder="请输入新密码"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="确认密码"
            v-show="active === 0"
            prop="confirmPassword"
          >
            <el-input
              type="password"
              v-model="formValidate.confirmPassword"
              placeholder="请再次输入密码"
              clearable
            />
          </el-form-item>
          <div v-show="active === 1" style="color: green; font-size: 18px">
            修改成功！
          </div>
          <div v-show="active === 2" style="color: green; font-size: 18px">
            请重新登录
          </div>
          <el-button
            style="margin-top: 12px"
            @click="next"
            v-show="active === 2"
          >
            <router-link to="/login" style="text-decoration: none"
              >去登录</router-link
            >
          </el-button>
        </el-form>

        <div
          style="display: flex; justify-content: center; margin-top: 20px"
          v-show="active === 0"
        >
          <el-button style="margin-top: 12px" @click="confirm"
            >确认修改</el-button
          >
        </div>
        <template #footer>
          <div
            style="display: flex; justify-content: center; margin-top: 20px"
            v-show="active === 1"
          >
            <el-button style="margin-top: 12px" @click="next">
              <router-link to="/login">去登录</router-link>
            </el-button>
          </div>
        </template>
      </el-card>
    </div>
    <div class="feature-container">
      <el-footer>管理平台 ©2024 Created by seventeen</el-footer>
    </div>
  </div>
</template>

<style scoped>
.feature-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  margin-top: 100px;
  position: relative;
  z-index: 1;
}
</style>
